import { EnumTagType, type EnumEducation, type JobDetailResult, type JobEditStep2Request } from "@/api/siderBar/model"
import { filterOption } from '@/utils/helper';
import type { RouteParams } from "../types"
import { getJobGetschooltags, postJobJobstep2Id, postJobQuicktags } from "@/api/siderBar/job";
import { message } from "ant-design-vue";

interface FormState extends JobEditStep2Request {
  exp?: string | number
}
interface UseStepOneOptions {
    query: Ref<RouteParams>
    next: IFn
}
export function useStepTwo({ query, next }: UseStepOneOptions) {
    const submiting = ref<boolean>(false)
    const formState = ref<FormState>(getInitialFormState())
    const minAgeSelectOptions = ref<Array<IOption<number>>>([...Array(100)].slice(18, 66).map((_, n) => ({ value: n + 18, label: `${n + 18}岁` })))
    const maxAgeSelectOptions = ref<Array<IOption<number>>>(cloneDeep(toRaw(minAgeSelectOptions.value)))
    const eduOptions: Array<IOption<EnumEducation | ({} & number)>> = [
        { value: AllValue, label: '不限' },
        ...educationOptions
    ]
    const studentState = 3
    const expOptions: Array<IOption<string | number>> = [
        { value: AllValue, label: '不限' },
        { value: studentState, label: '在校生/应届生' },
        { value: '_1', label: '1年以内' },
        { value: '1_3', label: '1~3年' },
        { value: '3_5', label: '3~5年' },
        { value: '5_10', label: '5~10年' },
        { value: '10_', label: '10年以上' }
    ]
    const { data: _schoolTagOptions } = useRequest(() => getJobGetschooltags(), {
        cacheKey: "getJobGetschooltags",
        staleTime: 6000000,
        initialData: []
    })
    const schoolTagOptions = computed<Array<IOption<string>>>(() => {
        return [
            { value: AllValue, label: '不限' },
            ..._schoolTagOptions.value!
        ]
    })
    function handleSchoolTagsSelect(value: string) {
        const { schoolTags } = toValue(formState)
        if (isAllValue(value)) {
            formState.value.schoolTags.length = 0
            formState.value.schoolTags.push(AllValue as any)
        } else if (schoolTags.includes(AllValue as any)) {
            formState.value.schoolTags.length = 0
            formState.value.schoolTags.push(value)
        } else if (schoolTags.length === toValue(_schoolTagOptions)!.length) {
            formState.value.schoolTags.length = 0
            formState.value.schoolTags.push(AllValue as any)
        }
    }
    function handleSchoolTagsDeSelect(value: string) {
        const { schoolTags } = toValue(formState)
        if (isAllValue(value) || schoolTags.length === 0) {
            formState.value.schoolTags.length = 0
            formState.value.schoolTags.push(AllValue as any)
        }
    }
    function getInitialFormState(): FormState {
        return {
            education: AllValue as any,
            exp: AllValue as any,
            skillTagIds: [],
            experienceTagIds: [],
            schoolTags: [AllValue as any]
        }
    }
    async function populateDetail(detail:JobDetailResult) {
        if (!detail) return
        ; (<const>["ageMin", "ageMax", "education"]).forEach(field => {
            if (isSetValue(detail[field])) {
                // @ts-ignore
                formState.value[field] = detail[field]
            }
        })
        if (isSetValue(detail.studentState)) {
            formState.value.exp = detail.studentState
        } else if (isSetValue(detail.experienceMin) || isSetValue(detail.experienceMax)) {
            formState.value.exp = [detail.experienceMin ?? '', detail.experienceMax ?? ''].join('_')
        }
        if (isSetValue(detail.skillTags)) {
            formState.value.skillTagIds = detail.skillTags.map(l => l.value)
        }
        if (isSetValue(detail.experienceTags)) {
            formState.value.experienceTagIds = detail.experienceTags.map(l => l.value)
        }
        if (isSetValue(detail.schoolTags) && detail.schoolTags.length > 0) {
            formState.value.schoolTags = detail.schoolTags
        }
    }
    function handleAgeRangeChange() {
        const { ageMin: min, ageMax: max } = toValue(formState)
        const minSet = isSetValue(min)
        const maxSet = isSetValue(max)
        if (minSet && !maxSet) {
            maxAgeSelectOptions.value.forEach(l => {
                l.disabled = l.value <= min
            })
            minAgeSelectOptions.value.forEach(l => {
                l.disabled = false
            })
        } else if (!minSet && maxSet) {
            minAgeSelectOptions.value.forEach(l => {
                l.disabled = l.value >= max
            })
            maxAgeSelectOptions.value.forEach(l => {
                l.disabled = false
            })
        } else if (!minSet && !maxSet) {
            minAgeSelectOptions.value.forEach(l => {
                l.disabled = false
            })
            maxAgeSelectOptions.value.forEach(l => {
                l.disabled = false
            })
        }
    }
    async function save() {
        const state = toValue(formState)
        // validate && collect
        const params = <JobEditStep2Request>{};
        ; (<const>["ageMin", "ageMax"]).forEach(field => {
            if (state[field] && !Number.isNaN(Number(state[field]))) {
                params[field] = Number(state[field])
            }
        })
        if (isSetValue(state.education) && !Object.is(state.education, AllValue)) {
            params.education = state.education
        }
        if (isSetValue(state.exp) && !Object.is(state.exp, AllValue)) {
            if (Object.is(state.exp, studentState)) {
                params.studentState = studentState
            } else {
                const [min, max] = (<string>state.exp).split('_')
                if (min) {
                    params.experienceMin = Number(min)
                }
                if (max) {
                    params.experienceMax = Number(max)
                }
            }
        }
        if (state.schoolTags) {
            params.schoolTags = state.schoolTags.filter(value => !isAllValue(value))
        }
        if (state.skillTagIds && state.skillTagIds.length > 0) {
            params.skillTagIds = state.skillTagIds
        }
        if (state.experienceTagIds && state.experienceTagIds.length > 0) {
            params.experienceTagIds = state.experienceTagIds
        }
        // submit
        try {
            submiting.value = true
            await postJobJobstep2Id(Number(query.value.id || 0), params)
            message.success('保存成功')
            next()
        } finally {
            submiting.value = false
        }
    }
    function getTagOptions(tagType: 'skill' | 'exp', text: string) {
        return postJobQuicktags({
            keywords: text,
            top: 20,
            defaultValues: tagType === 'skill' ? formState.value.skillTagIds : formState.value.experienceTagIds,
            tagType: tagType === 'skill' ? EnumTagType.技能标签 : EnumTagType.项目经验
        }).then(tags => tags.map(tag => ({ value: tag.value, label: tag.label, disabled: tag.disabled })))
    }
    return {
        filterOption,
        submiting,
        formState,
        minAgeSelectOptions,
        maxAgeSelectOptions,
        eduOptions,
        expOptions,
        schoolTagOptions,
        handleSchoolTagsSelect,
        handleSchoolTagsDeSelect,
        populateDetail,
        handleAgeRangeChange,
        save,
        getSkillTagOptions: getTagOptions.bind(null, 'skill'),
        getExpTagOptions: getTagOptions.bind(null, 'exp'),
    }
}